<template>
  <div class="user-management">
    <div class="management-header">
      <h2>用户管理</h2>
      <button class="add-user-btn" @click="showAddUserModal">
        <svg width="16" height="16" viewBox="0 0 24 24" fill="none">
          <path d="M12 5V19M5 12H19" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
        </svg>
        添加用户
      </button>
    </div>

    <!-- 搜索和筛选 -->
    <div class="search-filters">
      <div class="search-box">
        <input 
          v-model="searchParams.userAccount" 
          type="text" 
          placeholder="搜索用户账号"
          @input="handleSearch"
        />
      </div>
      <div class="search-box">
        <input 
          v-model="searchParams.userName" 
          type="text" 
          placeholder="搜索用户昵称"
          @input="handleSearch"
        />
      </div>
      <div class="filter-box">
        <select v-model="searchParams.userRole" @change="handleSearch">
          <option value="">全部角色</option>
          <option value="user">普通用户</option>
          <option value="admin">管理员</option>
        </select>
      </div>
    </div>

    <!-- 用户列表 -->
    <div class="user-table-container">
      <table class="user-table">
        <thead>
          <tr>
            <th>ID</th>
            <th>头像</th>
            <th>账号</th>
            <th>昵称</th>
            <th>角色</th>
            <th>创建时间</th>
            <th>操作</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="user in userList" :key="user.id">
            <td>{{ user.id }}</td>
            <td>
              <div class="user-avatar">
                <img v-if="user.userAvatar" :src="user.userAvatar" :alt="user.userName" />
                <div v-else class="default-avatar">
                  {{ (user.userName || user.userAccount || 'U').charAt(0).toUpperCase() }}
                </div>
              </div>
            </td>
            <td>{{ user.userAccount }}</td>
            <td>{{ user.userName || '-' }}</td>
            <td>
              <span class="role-badge" :class="user.userRole">
                {{ user.userRole === 'admin' ? '管理员' : '普通用户' }}
              </span>
            </td>
            <td>{{ formatDate(user.createTime) }}</td>
            <td>
              <div class="action-buttons">
                <button class="edit-btn" @click="editUser(user)" title="编辑">
                  <svg width="14" height="14" viewBox="0 0 24 24" fill="none">
                    <path d="M11 4H4C3.46957 4 2.96086 4.21071 2.58579 4.58579C2.21071 4.96086 2 5.46957 2 6V20C2 20.5304 2.21071 21.0391 2.58579 21.4142C2.96086 21.7893 3.46957 22 4 22H18C18.5304 22 19.0391 21.7893 19.4142 21.4142C19.7893 21.0391 20 20.5304 20 20V13" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
                    <path d="M18.5 2.50023C18.8978 2.10243 19.4374 1.87891 20 1.87891C20.5626 1.87891 21.1022 2.10243 21.5 2.50023C21.8978 2.89804 22.1213 3.43762 22.1213 4.00023C22.1213 4.56284 21.8978 5.10243 21.5 5.50023L12 15.0002L8 16.0002L9 12.0002L18.5 2.50023Z" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
                  </svg>
                </button>
                <button class="delete-btn" @click="deleteUser(user)" title="删除">
                  <svg width="14" height="14" viewBox="0 0 24 24" fill="none">
                    <path d="M3 6H5H21" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
                    <path d="M8 6V4C8 3.46957 8.21071 2.96086 8.58579 2.58579C8.96086 2.21071 9.46957 2 10 2H14C14.5304 2 15.0391 2.21071 15.4142 2.58579C15.7893 2.96086 16 3.46957 16 4V6M19 6V20C19 20.5304 18.7893 21.0391 18.4142 21.4142C18.0391 21.7893 17.5304 22 17 22H7C6.46957 22 5.96086 21.7893 5.58579 21.4142C5.21071 21.0391 5 20.5304 5 20V6H19Z" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
                  </svg>
                </button>
              </div>
            </td>
          </tr>
        </tbody>
      </table>
    </div>

    <!-- 分页 -->
    <div class="pagination">
      <button 
        class="page-btn" 
        :disabled="currentPage <= 1" 
        @click="changePage(currentPage - 1)"
      >
        上一页
      </button>
      <span class="page-info">
        第 {{ currentPage }} 页，共 {{ totalPages }} 页，总计 {{ total }} 条记录
      </span>
      <button 
        class="page-btn" 
        :disabled="currentPage >= totalPages" 
        @click="changePage(currentPage + 1)"
      >
        下一页
      </button>
    </div>

    <!-- 添加/编辑用户弹窗 -->
    <div v-if="showUserModal" class="modal-overlay" @click="closeUserModal">
      <div class="modal-content" @click.stop>
        <div class="modal-header">
          <h3>{{ isEditing ? '编辑用户' : '添加用户' }}</h3>
          <button class="close-btn" @click="closeUserModal">
            <svg width="20" height="20" viewBox="0 0 24 24" fill="none">
              <path d="M18 6L6 18M6 6L18 18" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
            </svg>
          </button>
        </div>
        <div class="modal-body">
          <form @submit.prevent="saveUser">
            <div class="form-group">
              <label>用户账号 *</label>
              <input 
                v-model="userForm.userAccount" 
                type="text" 
                required 
                :disabled="isEditing"
                placeholder="请输入用户账号"
              />
            </div>
            <div class="form-group">
              <label>用户昵称</label>
              <input 
                v-model="userForm.userName" 
                type="text" 
                placeholder="请输入用户昵称"
              />
            </div>
            <div class="form-group">
              <label>用户头像</label>
              <input 
                v-model="userForm.userAvatar" 
                type="url" 
                placeholder="请输入头像URL"
              />
            </div>
            <div class="form-group">
              <label>用户简介</label>
              <textarea 
                v-model="userForm.userProfile" 
                placeholder="请输入用户简介"
                rows="3"
              ></textarea>
            </div>
            <div class="form-group">
              <label>用户角色 *</label>
              <select v-model="userForm.userRole" required>
                <option value="user">普通用户</option>
                <option value="admin">管理员</option>
              </select>
            </div>
            <div class="form-actions">
              <button type="button" class="cancel-btn" @click="closeUserModal">
                取消
              </button>
              <button type="submit" class="save-btn" :disabled="loading">
                {{ loading ? '保存中...' : '保存' }}
              </button>
            </div>
          </form>
        </div>
      </div>
    </div>

    <!-- 删除确认弹窗 -->
    <div v-if="showDeleteModal" class="modal-overlay" @click="closeDeleteModal">
      <div class="modal-content delete-modal" @click.stop>
        <div class="modal-header">
          <h3>确认删除</h3>
        </div>
        <div class="modal-body">
          <p>确定要删除用户 "{{ userToDelete?.userName || userToDelete?.userAccount }}" 吗？</p>
          <p class="warning-text">此操作不可撤销！</p>
        </div>
        <div class="form-actions">
          <button type="button" class="cancel-btn" @click="closeDeleteModal">
            取消
          </button>
          <button type="button" class="delete-confirm-btn" @click="confirmDelete" :disabled="loading">
            {{ loading ? '删除中...' : '确认删除' }}
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, onBeforeUnmount } from 'vue'
import { userApi } from '../api/user'

// 响应式数据
const userList = ref([])
const loading = ref(false)
const showUserModal = ref(false)
const showDeleteModal = ref(false)
const isEditing = ref(false)
const userToDelete = ref(null)

// 分页数据
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const totalPages = ref(0)

// 搜索参数
const searchParams = reactive({
  userAccount: '',
  userName: '',
  userRole: ''
})

// 用户表单
const userForm = reactive({
  id: null,
  userAccount: '',
  userName: '',
  userAvatar: '',
  userProfile: '',
  userRole: 'user'
})

// 获取用户列表
const getUserList = async () => {
  try {
    loading.value = true
    const params = {
      current: currentPage.value,
      pageSize: pageSize.value,
      ...searchParams
    }
    
    // 过滤空值
    Object.keys(params).forEach(key => {
      if (params[key] === '') {
        delete params[key]
      }
    })
    
    const response = await userApi.getUserList(params)
    if (response.code === 0) {
      userList.value = response.data.records || []
      total.value = response.data.total || 0
      totalPages.value = Math.ceil(total.value / pageSize.value)
    } else {
      console.error('获取用户列表失败:', response.message)
    }
  } catch (error) {
    console.error('获取用户列表失败:', error)
  } finally {
    loading.value = false
  }
}

// 搜索处理
const handleSearch = () => {
  currentPage.value = 1
  getUserList()
}

// 分页处理
const changePage = (page) => {
  currentPage.value = page
  getUserList()
}

// 显示添加用户弹窗
const showAddUserModal = () => {
  isEditing.value = false
  resetUserForm()
  showUserModal.value = true
}

// 编辑用户
const editUser = (user) => {
  isEditing.value = true
  Object.assign(userForm, {
    id: user.id,
    userAccount: user.userAccount,
    userName: user.userName || '',
    userAvatar: user.userAvatar || '',
    userProfile: user.userProfile || '',
    userRole: user.userRole
  })
  showUserModal.value = true
}

// 重置用户表单
const resetUserForm = () => {
  Object.assign(userForm, {
    id: null,
    userAccount: '',
    userName: '',
    userAvatar: '',
    userProfile: '',
    userRole: 'user'
  })
}

// 保存用户
const saveUser = async () => {
  try {
    loading.value = true
    
    if (isEditing.value) {
      // 编辑用户
      const response = await userApi.updateUser(userForm)
      if (response.code === 0) {
        console.log('用户更新成功')
        closeUserModal()
        getUserList()
      } else {
        console.error('用户更新失败:', response.message)
      }
    } else {
      // 添加用户
      const response = await userApi.addUser(userForm)
      if (response.code === 0) {
        console.log('用户添加成功')
        closeUserModal()
        getUserList()
      } else {
        console.error('用户添加失败:', response.message)
      }
    }
  } catch (error) {
    console.error('保存用户失败:', error)
  } finally {
    loading.value = false
  }
}

// 删除用户
const deleteUser = (user) => {
  userToDelete.value = user
  showDeleteModal.value = true
}

// 确认删除
const confirmDelete = async () => {
  try {
    loading.value = true
    const response = await userApi.deleteUser(userToDelete.value.id)
    if (response.code === 0) {
      console.log('用户删除成功')
      closeDeleteModal()
      getUserList()
    } else {
      console.error('用户删除失败:', response.message)
    }
  } catch (error) {
    console.error('用户删除失败:', error)
  } finally {
    loading.value = false
  }
}

// 关闭用户弹窗
const closeUserModal = () => {
  showUserModal.value = false
  resetUserForm()
}

// 关闭删除弹窗
const closeDeleteModal = () => {
  showDeleteModal.value = false
  userToDelete.value = null
}

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return '-'
  const date = new Date(dateString)
  return date.toLocaleDateString('zh-CN') + ' ' + date.toLocaleTimeString('zh-CN', { hour12: false })
}

// 组件挂载时获取用户列表
onMounted(() => {
  getUserList()
  // 监听登录完成事件（例如登录后触发的全局事件），重新拉取列表
  const handler = () => getUserList()
  window.addEventListener('user-login', handler)
  // 存在响应拦截器触发的 user-logout 时，也可以根据需要清空列表或跳转
  window.addEventListener('user-logout', handler)
  // 缓存到实例上以便卸载时移除
  ;(window).__umHandlers = handler
})

onBeforeUnmount(() => {
  const handler = (window).__umHandlers
  if (handler) {
    window.removeEventListener('user-login', handler)
    window.removeEventListener('user-logout', handler)
    delete (window).__umHandlers
  }
})
</script>

<style scoped>
.user-management {
  padding: 20px;
  background: rgba(0, 0, 0, 0.8);
  min-height: calc(100vh - 70px);
  color: #fff;
}

.management-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30px;
}

.management-header h2 {
  margin: 0;
  font-size: 24px;
  font-weight: 600;
}

.add-user-btn {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 10px 20px;
  background: linear-gradient(45deg, #ff6b6b, #4ecdc4);
  color: #fff;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  font-size: 14px;
  font-weight: 500;
  transition: all 0.3s ease;
}

.add-user-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 15px rgba(255, 107, 107, 0.4);
}

.search-filters {
  display: flex;
  gap: 15px;
  margin-bottom: 20px;
  flex-wrap: wrap;
}

.search-box input,
.filter-box select {
  padding: 10px 15px;
  background: rgba(255, 255, 255, 0.1);
  border: 1px solid rgba(255, 255, 255, 0.2);
  border-radius: 6px;
  color: #fff;
  font-size: 14px;
  min-width: 200px;
}

.search-box input::placeholder {
  color: rgba(255, 255, 255, 0.6);
}

.filter-box select option {
  background: rgba(20, 20, 20, 0.9);
  color: #fff;
}

.user-table-container {
  background: rgba(255, 255, 255, 0.05);
  border-radius: 8px;
  overflow: hidden;
  margin-bottom: 20px;
}

.user-table {
  width: 100%;
  border-collapse: collapse;
}

.user-table th,
.user-table td {
  padding: 15px;
  text-align: left;
  border-bottom: 1px solid rgba(255, 255, 255, 0.1);
}

.user-table th {
  background: rgba(255, 255, 255, 0.1);
  font-weight: 600;
  font-size: 14px;
}

.user-table td {
  font-size: 14px;
}

.user-avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  overflow: hidden;
  display: flex;
  align-items: center;
  justify-content: center;
}

.user-avatar img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.default-avatar {
  width: 100%;
  height: 100%;
  background: linear-gradient(45deg, #ff6b6b, #4ecdc4);
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: 600;
  font-size: 16px;
}

.role-badge {
  padding: 4px 12px;
  border-radius: 12px;
  font-size: 12px;
  font-weight: 500;
}

.role-badge.admin {
  background: rgba(255, 107, 107, 0.2);
  color: #ff6b6b;
  border: 1px solid rgba(255, 107, 107, 0.3);
}

.role-badge.user {
  background: rgba(78, 205, 196, 0.2);
  color: #4ecdc4;
  border: 1px solid rgba(78, 205, 196, 0.3);
}

.action-buttons {
  display: flex;
  gap: 8px;
}

.edit-btn,
.delete-btn {
  padding: 6px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
  justify-content: center;
}

.edit-btn {
  background: rgba(78, 205, 196, 0.2);
  color: #4ecdc4;
}

.edit-btn:hover {
  background: rgba(78, 205, 196, 0.3);
}

.delete-btn {
  background: rgba(255, 107, 107, 0.2);
  color: #ff6b6b;
}

.delete-btn:hover {
  background: rgba(255, 107, 107, 0.3);
}

.pagination {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 20px;
}

.page-btn {
  padding: 8px 16px;
  background: rgba(255, 255, 255, 0.1);
  color: #fff;
  border: 1px solid rgba(255, 255, 255, 0.2);
  border-radius: 6px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.page-btn:hover:not(:disabled) {
  background: rgba(255, 255, 255, 0.2);
}

.page-btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.page-info {
  font-size: 14px;
  color: rgba(255, 255, 255, 0.8);
}

/* 弹窗样式 */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.7);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 2000;
}

.modal-content {
  background: rgba(20, 20, 20, 0.95);
  backdrop-filter: blur(10px);
  border: 1px solid rgba(255, 255, 255, 0.1);
  border-radius: 12px;
  width: 90%;
  max-width: 500px;
  max-height: 90vh;
  overflow-y: auto;
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  border-bottom: 1px solid rgba(255, 255, 255, 0.1);
}

.modal-header h3 {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
}

.close-btn {
  background: none;
  border: none;
  color: rgba(255, 255, 255, 0.6);
  cursor: pointer;
  padding: 4px;
  border-radius: 4px;
  transition: all 0.3s ease;
}

.close-btn:hover {
  color: #fff;
  background: rgba(255, 255, 255, 0.1);
}

.modal-body {
  padding: 20px;
}

.form-group {
  margin-bottom: 20px;
}

.form-group label {
  display: block;
  margin-bottom: 8px;
  font-size: 14px;
  font-weight: 500;
  color: rgba(255, 255, 255, 0.9);
}

.form-group input,
.form-group select,
.form-group textarea {
  width: 100%;
  padding: 12px 15px;
  background: rgba(255, 255, 255, 0.1);
  border: 1px solid rgba(255, 255, 255, 0.2);
  border-radius: 6px;
  color: #fff;
  font-size: 14px;
  box-sizing: border-box;
}

.form-group input::placeholder,
.form-group textarea::placeholder {
  color: rgba(255, 255, 255, 0.6);
}

.form-group input:focus,
.form-group select:focus,
.form-group textarea:focus {
  outline: none;
  border-color: #4ecdc4;
  box-shadow: 0 0 0 2px rgba(78, 205, 196, 0.2);
}

.form-group input:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

.form-group select option {
  background: rgba(20, 20, 20, 0.9);
  color: #fff;
}

.form-actions {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  margin-top: 30px;
}

.cancel-btn,
.save-btn,
.delete-confirm-btn {
  padding: 10px 20px;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  font-size: 14px;
  font-weight: 500;
  transition: all 0.3s ease;
}

.cancel-btn {
  background: rgba(255, 255, 255, 0.1);
  color: rgba(255, 255, 255, 0.8);
  border: 1px solid rgba(255, 255, 255, 0.2);
}

.cancel-btn:hover {
  background: rgba(255, 255, 255, 0.2);
  color: #fff;
}

.save-btn {
  background: linear-gradient(45deg, #4ecdc4, #44a08d);
  color: #fff;
}

.save-btn:hover:not(:disabled) {
  transform: translateY(-1px);
  box-shadow: 0 4px 15px rgba(78, 205, 196, 0.4);
}

.delete-confirm-btn {
  background: linear-gradient(45deg, #ff6b6b, #ee5a52);
  color: #fff;
}

.delete-confirm-btn:hover:not(:disabled) {
  transform: translateY(-1px);
  box-shadow: 0 4px 15px rgba(255, 107, 107, 0.4);
}

.save-btn:disabled,
.delete-confirm-btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
  transform: none;
  box-shadow: none;
}

.delete-modal {
  max-width: 400px;
}

.warning-text {
  color: #ff6b6b;
  font-size: 14px;
  margin-top: 10px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .user-management {
    padding: 15px;
  }
  
  .management-header {
    flex-direction: column;
    gap: 15px;
    align-items: flex-start;
  }
  
  .search-filters {
    flex-direction: column;
  }
  
  .search-box input,
  .filter-box select {
    min-width: 100%;
  }
  
  .user-table-container {
    overflow-x: auto;
  }
  
  .user-table {
    min-width: 800px;
  }
  
  .modal-content {
    width: 95%;
    margin: 20px;
  }
}
</style>